// Copyright 2010 Google Inc. All Rights Reserved.

package com.google.zahra.webmanager;

import com.google.zahra.testmanager.Test;
import com.google.zahra.testmanager.TestManager;
import com.google.zahra.util.Util;

import commonj.work.WorkException;
import commonj.work.WorkItem;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author arthurkok@google.com (Your Name Here)
 *
 */

public class TestServlet extends HttpServlet {
  
  static final TestManager testManager = WebManager.TEST_MANAGER;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    String jobIdString = request.getParameter("jobId");
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    StringBuffer bodyString = new StringBuffer();
    
    bodyString.append("<h2>Job ID: " + jobIdString +"</h2>");
    
    try {
      int jobId = Integer.parseInt(jobIdString);
      Object row = testManager.model.getValueAt(jobId, 0);

      for (int col = 0; col < 3; col++) {

        bodyString.append("<h2>" + Util.getOsName((int) Math.pow(2, col)) + "</h2>");
        WorkItem workItem = (WorkItem) testManager.model.getValueAt(jobId, col+1);

        if (workItem == null) {
          bodyString.append("No test scheduled for this os");
          continue;
        }

        Test test;
        try {         
          test = (Test) workItem.getResult();
        } catch (WorkException e) {
          bodyString.append("The test threw an exception:" + e);
          continue;
        }

        bodyString.append("Status: " + workItem + "<br/> ");
                
        bodyString.append("<textarea cols='80' rows='10'>" + test + "</textarea>");
        bodyString.append("<textarea cols='80' rows='10'>" +  new String(test.file) + "</textarea>");

      }

    } catch (ArrayIndexOutOfBoundsException ex) {
      bodyString.append("Job does not exist!");
    } catch (NumberFormatException ex) {
      bodyString.append("Malformed test JobId!");
    }

    response.getWriter().print(Util.getHTML(bodyString.toString(), "Zahra - Test"));

  }
}
